package com.qiche.controller.mgr;

import com.qiche.aspect.Result;
import com.qiche.constant.PayStatus;
import com.qiche.dto.MemberSubscribeDetailDto;
import com.qiche.dto.PCUserSubscribeDto;
import com.qiche.dto.SubscribeForm;
import com.qiche.dto.UserSubscribeDetaiDto;
import com.qiche.enums.ResultEnum;
import com.qiche.enums.SubscribeStatusEnum;
import com.qiche.model.*;
import com.qiche.requestpram.SubscribeParam;
import com.qiche.service.*;
import com.qiche.util.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Api(value = "/subscribe",description = "预约或服务记录管理控制器")
@RestController
@RequestMapping("/subscribe")
public class SubscribeController {

    @Autowired
    private SubscribeService subscribeService;
    @Autowired
    private SubscribeProductService subscribeProductService;

    @Autowired
    private StoreMemberCarService storeMemberCarService;
    @Autowired
    private StoreMemberService storeMemberService;
    @Autowired
    private WorkstageService workstageService;
    @Autowired
    private ServiceItemWorkstageService serviceItemWorkstageService;

    @ApiOperation(value = "PC端根据条件和分页获取预约列表")
    @GetMapping("/subscribeList")
    public Map<String, Object> getAllSubscribeList(SubscribeForm param,
                                           @RequestParam(required = false, defaultValue = "1") int page,
                                           @RequestParam(required = false, defaultValue = "10") int limit) {
        Map<String, Object> map = new HashMap<>();

        SubscribeParam queryParam = new SubscribeParam();
        queryParam.setStartTime(param.getStartDate());
        queryParam.setEndTime(param.getEndDate());
        queryParam.setSubscribeStatus(param.getStatus());
        queryParam.setProductName(param.getProductName());
        queryParam.setKeyword(param.getKeyword());
        queryParam.setPageNo(page);
        queryParam.setPageSize(limit);
        queryParam.setMerchantId(param.getMerchantId());
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        PCUserSubscribeDto dto = subscribeService.userSubscribeByParam(currentUser, queryParam);

        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", dto.getSubscribeParam().getTotal());
        map.put("data", dto.getSubscribeDetailDtos());
        return map;
    }

    @ApiOperation(value = "PC端根据条件和分页获取服务记录列表")
    @GetMapping("serviceList")
    public Map<String, Object> getAllServiceList(SubscribeForm param,
                                          @RequestParam(required = false, defaultValue = "1") int page,
                                          @RequestParam(required = false, defaultValue = "10") int limit) {
        Map<String, Object> map = new HashMap<>();

        SubscribeParam queryParam = new SubscribeParam();
        queryParam.setStartTime(param.getStartDate());
        queryParam.setEndTime(param.getEndDate());
        queryParam.setSubscribeStatus(param.getStatus());
        queryParam.setProductName(param.getProductName());
        queryParam.setKeyword(param.getKeyword());
        queryParam.setPayStatus(param.getPayStatus());
        queryParam.setPageNo(page);
        queryParam.setPageSize(limit);
        queryParam.setMerchantId(param.getMerchantId());
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        PCUserSubscribeDto dto = subscribeService.userServiceByParam(currentUser, queryParam);
        dto.getSubscribeDetailDtos();
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", dto.getSubscribeParam().getTotal());
        map.put("data", dto.getSubscribeDetailDtos());
        return map;
    }

    @ApiOperation(value = "PC端根据ID获取预约信息")
    @GetMapping("/getById/{id}")
    public Result getById(@PathVariable("id") Long id) {
        if (id == null || id <= 0) {
            return Result.createByResultEnum(ResultEnum.PARAM_ERROR);
        }
        Subscribe subscribe = subscribeService.selectByKey(id);
        SubscribeForm form = new SubscribeForm();
        form.setCustomerId(subscribe.getCustomerId());
        form.setStatus(subscribe.getSubscribeStatus());
        form.setOrderTime(subscribe.getCreateTime());
        // 只能根据车牌号码去查
        StoreMemberCar storeMemberCar=storeMemberCarService.selectByKey(subscribe.getCustomerCarId());

        if (storeMemberCar != null) {
            form.setCustomerCarId(storeMemberCar.getId());
        }
        List<Product> products = subscribeProductService.selectProductBySubscribeId(subscribe.getSubscribeId());
        if (products != null && products.size() > 0) {
            form.setProductId(products.get(0).getId());
        }
        return Result.createByResultEnum(ResultEnum.SUCCESS, form);
    }

    @ApiOperation(value = "开单")
    @PostMapping("/open")
    public Result openSubscribe(Long subcribeId) {
        List<SubscribeProduct> subscribeProducts=subscribeProductService.selectBySubscribeId(subcribeId);
        for (SubscribeProduct subscribeProduct: subscribeProducts) {
            if(workstageService.selectByItemId(subscribeProduct.getProductId()).size()!=0){
                serviceItemWorkstageService.generateWorkstageBySubproId(subscribeProduct.getSubProId());
                int stageCount=serviceItemWorkstageService.countBySubproId(subscribeProduct.getSubProId());
                Subscribe tempSubscribe=new Subscribe();
                tempSubscribe.setSubscribeId(subcribeId);
                tempSubscribe.setProgress("0/"+stageCount);
                int updateCount= subscribeService.updateNotNull(tempSubscribe);
            }

        }
        return subscribeService.updateSubscribeStatus(subcribeId, SubscribeStatusEnum.OPEN_SUBSCRIBE.getStatus());
    }

    @ApiOperation(value = "取消预约")
    @PostMapping("/cancel")
    public Result cancelSubscribe(Long subcribeId) {
        return subscribeService.updateSubscribeStatus(subcribeId, SubscribeStatusEnum.CANCEL.getStatus());
    }

    @ApiOperation(value = "结算")
    @PostMapping("/finish")
    public Result finishSubscribe(Long subcribeId) {
        return subscribeService.updateSubscribeStatus(subcribeId, SubscribeStatusEnum.CLOSE_SUBSCRIBE.getStatus());
    }

    @ApiOperation(value = "PC端保存预约")
    @PostMapping("/add")
    public Result add(@RequestBody SubscribeForm form) {
        try {
            Subscribe subscribe = new Subscribe();
            subscribe.setCustomerId(form.getCustomerId());
            StoreMemberCar  storeMemberCar=storeMemberCarService.selectByKey(form.getCustomerCarId());
            subscribe.setCustomerId(storeMemberCar.getStoreMemberId());
            subscribe.setCustomerCarId(storeMemberCar.getId());
            subscribe.setCustomerCarDesc(storeMemberCar.getCarInfo());
            subscribe.setCarNum(storeMemberCar.getPlateNumber());
            subscribe.setFrameNum(storeMemberCar.getFrameNumber());
            subscribe.setSubscribeStatus(form.getStatus());
            subscribe.setSubscribeTime(form.getOrderTime());
            subscribe.setCreateTime(new Date());
            subscribe.setPayStatus(PayStatus.PAY_NON);
            subscribe.setMerchantId(UserUtils.getCurrentUser().getMerchantId().longValue());
            List<Long> productIds = new ArrayList<>();
            productIds.add(form.getProductId());
            Result insert = subscribeService.userSubscribe(subscribe, productIds);
            if (insert.isSuccess()) {
                return Result.createByResultEnum(ResultEnum.SUCCESS, subscribe);
            } else {
                return Result.createByResultEnum(ResultEnum.FAILURE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.createByResultEnum(ResultEnum.UNKONW_ERROR);
        }
    }

    @ApiOperation(value = "PC端更新预约")
    @PutMapping("/update")
    public Result update(@RequestBody SubscribeForm form) {
        try {
            Subscribe subscribe = new Subscribe();
            subscribe.setCustomerId(form.getCustomerId());
            StoreMemberCar storeMemberCar =storeMemberCarService.selectByKey(form.getCustomerCarId());
            subscribe.setCustomerId(storeMemberCar.getStoreMemberId());
            subscribe.setCustomerCarId(storeMemberCar.getId());
            subscribe.setCustomerCarDesc(storeMemberCar.getCarInfo());
            subscribe.setCarNum(storeMemberCar.getPlateNumber());
            subscribe.setFrameNum(storeMemberCar.getFrameNumber());
            subscribe.setSubscribeStatus(form.getStatus());
            subscribe.setCreateTime(new Date());
            subscribe.setSubscribeTime(form.getOrderTime());
            subscribe.setSubscribeId(form.getSubscribeId());
            subscribe.setMerchantId(UserUtils.getCurrentUser().getMerchantId().longValue());
            List<Long> productIds = new ArrayList<>();
            productIds.add(form.getProductId());

           int update= subscribeService.userSubscribeUpdate(subscribe,productIds);

            if (update > 0) {
                return Result.createByResultEnum(ResultEnum.SUCCESS, subscribe);
            } else {
                return Result.createByResultEnum(ResultEnum.FAILURE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.createByResultEnum(ResultEnum.UNKONW_ERROR);
        }
    }


    @ApiOperation(value = "PC端删除预约")
    @PostMapping("/delete")
    public Result delete(@RequestParam Long id) {
        int delete = subscribeService.delete(id);
        int subDelete = subscribeProductService.deleteBySubscribeId(id);
        if (delete > 0 && subDelete > 0) {
            return Result.createByResultEnum(ResultEnum.SUCCESS);
        } else {
            return Result.createByResultEnum(ResultEnum.FAILURE);
        }
    }

    @GetMapping("/service/{subcribeId}")
    public Result userGetSubscribeDetail(@PathVariable Long subcribeId) {

        Subscribe subscribe = subscribeService.selectByKey(subcribeId);
        if (subscribe == null) {
            return Result.createByResultEnum(ResultEnum.SUBSCRIBE_NOT_EXIST_ERROR);
        }
        UserSubscribeDetaiDto userSubscribeDetaiDto = subscribeService.userSubscribeDetail(subscribe);
        return Result.createByResultEnum(ResultEnum.SUCCESS, userSubscribeDetaiDto);
    }

    @ApiOperation(value = "根据客户ID获取服务记录列表")
    @GetMapping("/getServiceListByCustomerId/{customerId}")
    public Result<List<MemberSubscribeDetailDto> > getServiceListByCustomerId(@PathVariable("customerId") Long customerId){
        List<Subscribe> subscribeList= subscribeService.getServiceListByCustomerId(customerId);
        List<MemberSubscribeDetailDto> collect=new ArrayList<>();
        for (Subscribe subscribe:subscribeList) {
            collect.add( subscribeService.memberSubscribeDetail(subscribe));

        }
       return Result.createBySuccess(collect);
    }

}
